<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Shop_ip extends AdminController
{
    public $_validation = null;

    function __construct()
    {
        parent::__construct();
        $this->_validation = Array(
            array('field' => 'ip', 'label' => 'IP', 'rules' => 'trim|required')
        , array('field' => 'shop_id', 'label' => '所属账户', 'rules' => '')
        , array('field' => 'remark', 'label' => '备注', 'rules' => '')
        , array('field' => 'update_time', 'label' => '更新时间', 'rules' => '')
        );
    }

    public function index()
    {
        $this->load->model('MShopIp');
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->formfilter->addFilter('ip', 'where');

        $search_ip = filterValue('ip');
        if ($begintime = filterValue('ip_create_time_begin')) {
            $this->formfilter->addFilter('ip_create_time_begin', 'where', array('create_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('ip_create_time_end')) {
            $this->formfilter->addFilter('ip_create_time_end', 'where', array('create_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        $number_perpage = filterValue('ip_number_perpage');
        $order_type = filterValue('ip_order_type');

        $total_number = $this->MShopIp->getCount();
        $limit = $this->pagination($total_number, '', $number_perpage);
        $list = $this->MShopIp->getList($limit, $order_type);
//        var_export($this->getIP());
        $this->assign('list', $list);
        $this->assign('search_ip', $search_ip);
        $this->layout();
    }

    public function importExcel()
    {
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');
        $file = $_FILES ['file'] ['tmp_name']; //临时文件


        $file_type = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        if ($file_type == 'xlsx') {
            $objReader = IOFactory::createReader('Excel2007');

        } else {
            $objReader = IOFactory::createReader('Excel5');
        }
        $objPHPExcel = $objReader->load($file);

        //获取sheet表格数目
        $sheetCount = $objPHPExcel->getSheetCount();

        //默认选中sheet0表
        $sheetSelected = 0;
        $objPHPExcel->setActiveSheetIndex($sheetSelected);

        //获取表格列数
        $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn(2);

        $new = $objPHPExcel->getActiveSheet()->toArray();
        if (count($new) == 0) {
            echo '没有填数据，你导入个毛线';
            echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
            exit();
        }
        echo "<div>Sheet 数量 : " . $sheetCount . "　　行数： " . (count($new) - 1) . "　　列数：" . $columnCount . "</div>";

        $this->load->model('MShopIp');
        foreach ($new as $v) {

            $insert_arr['ip'] = $v[0];
            $insert_arr['remark'] = $v[1] ? $v[1] : '';
            $insert_arr['create_time'] = time();
            $insert_arr['update_time'] = time();
            if ($v[0]) {
                $sql = 'INSERT IGNORE INTO `core_shop_ip` (`ip`,`remark`,`create_time`,`update_time`) VALUES (?,?,?,?)';

                if ($this->db->query($sql, $insert_arr)) {
                    echo('<p style="color: #010202;">导入成功：ip（' . $v[0] . ' ），备注（ ' . $v[1] . '）<p>');
                } else {
                    echo('<p style="color:#ff4227">导入失败：已含有IP（' . $v[0] . '）的记录！<p>');
                }
            }
        }
        echo '<p>导入结束</p>';
        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
        exit();
    }

    public function ajaxAdd()
    {
        $data = $this->input->post();
        $this->load->model('MShopIp');
        $detail = $this->MShopIp->getOne(['ip' => $data['ip']]);
        if ($detail) {
            exit(json_encode([
                'success' => false,
                'msg' => '已存在该IP'
            ]));
        } else {
            $arr = ['ip' => $data['ip'], 'remark' => $data['remark'], 'create_time' => time(), 'update_time' => time()];
            if (!$this->MShopIp->add((object)$arr)) {
                exit(json_encode([
                    'success' => false,
                    'msg' => '试用失败'
                ]));
            } else {
                exit(json_encode([
                    'success' => true,
                    'msg' => '使用成功！'
                ]));
            }
        }
    }

    function getIP() /*获取客户端IP*/
    {
        if (@$_SERVER["HTTP_X_FORWARDED_FOR"])
            $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        else if (@$_SERVER["HTTP_CLIENT_IP"])
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        else if (@$_SERVER["REMOTE_ADDR"])
            $ip = $_SERVER["REMOTE_ADDR"];
        else if (@getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (@getenv("HTTP_CLIENT_IP"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (@getenv("REMOTE_ADDR"))
            $ip = getenv("REMOTE_ADDR");
        else
            $ip = "Unknown";
        return $ip;
    }


}
